﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows;
using System.Windows.Threading;

namespace CustomMapinfoWindows.ViewModels
{
    public class DirectoryViewModel : TreeViewItemViewModel, IHasPath
    {
        private FileSystemWatcher watcher;
        public DirectoryViewModel(string dirPath, TreeViewItemViewModel parent)
            : base(parent, true)
        {
            this.FullPath = dirPath;
            this.Name = new DirectoryInfo(dirPath).Name;
        }

        void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            var filestorename = this.GetModelWithPath(e.OldFullPath);

            foreach (IHasPath item in filestorename)
            {
                Dispatcher.CurrentDispatcher.Invoke(new Action(delegate()
                {
                    item.FullPath = e.FullPath;
                    item.Name = e.Name;
                }));
            }
        }

        void watcher_Created(object sender, FileSystemEventArgs e)
        {
            // HACK This is really nasty and really should be moved to a view model factory
            // that can handle it correctly.
            //if (File.Exists(e.FullPath))
            //{
                //string extension = Path.GetExtension(e.FullPath);
                //if (string.Compare(extension, ".tab", true) == 0)
                //{
                    base.Children.Add(new TabFileViewModel(e.FullPath, this, false));
                //}
                //else if(string.Compare(extension, ".wor", true) == 0)
                //{
                //    base.Children.Add(new WorkSpaceViewModel(e.FullPath, this));
                //}
                //return;
            //}

            //if (Directory.Exists(e.FullPath))
            //{
            //    base.Children.Add(new DirectoryViewModel(e.FullPath, this));
            //    return;
            //}
            
        }

        private string name;
        /// <summary>
        /// Gets or sets the friendly name for the directory.
        /// </summary>
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                base.OnPropertyChanged("Name");
            }
        }

        private string fullpath;
        /// <summary>
        /// Gets or sets the full path to the directory.
        /// </summary>
        public string FullPath
        {
            get
            {
                return this.fullpath;
            }
            set
            {
                this.fullpath = value;
                // We also have to update the file watcher to keep it in sync.
                if (this.IsWatchedForChanges)
                {
                    watcher.Path = this.fullpath;
                }
                base.OnPropertyChanged("FullPath");
            }
        }

        void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            this.RemoveFileFromChildren(e.FullPath);
        }

        private void RemoveFileFromChildren(string fullPath)
        {
            var filestoremove = this.GetModelWithPath(fullPath);

            foreach (TreeViewItemViewModel item in filestoremove.Cast<TreeViewItemViewModel>())
            {
                Dispatcher.CurrentDispatcher.Invoke(new Action(delegate()
                   {
                       base.Children.Remove(item);
                   }));
            }
        }

        private IEnumerable<IHasPath> GetModelWithPath(string fullPath)
        {
            var files = base.Children.Cast<IHasPath>()
                                            .Where(tab => tab.FullPath == fullPath).ToList();
            return files;
        }

        protected override void LoadChildren()
        {
            foreach (string dir in Directory.GetDirectories(this.FullPath))
            {
                base.Children.Add(new DirectoryViewModel(dir, this));
            }

            this.LoadTabFiles();
            this.LoadWorkSpaces();
        }

        private void LoadTabFiles()
        {
            foreach (var file in Directory.GetFiles(this.FullPath, "*.tab"))
            {
                base.Children.Add(new TabFileViewModel(file, this, false));
            }
        }

        private void LoadWorkSpaces()
        {
            foreach (var file in Directory.GetFiles(this.FullPath, "*.wor"))
            {
                base.Children.Add(new WorkSpaceViewModel(file, this));
            }
        }

        private bool iswatching;
        public bool IsWatchedForChanges
        {
            get
            {
                return (this.watcher != null && this.iswatching);
            }
            set
            {
                try
                {
                    if (this.watcher == null && value)
                    {
                        this.watcher = new FileSystemWatcher(this.FullPath);
                        this.watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;
                        this.watcher.Renamed += watcher_Renamed;
                        this.watcher.Deleted += watcher_Deleted;
                        this.watcher.Created += watcher_Created;
                        this.watcher.EnableRaisingEvents = true;
                        this.iswatching = true;
                    }
                    if (this.watcher != null && !value)
                    {
                        this.watcher = null;
                    }
                }
                catch (FileNotFoundException)
                {
                    this.watcher = null;
                    this.iswatching = false;
                }
            }
        }
    }
}
